
%% Check if this Boootstrap rep is already done:
% ES = exist(SaveBoot);
% if ES == 2
%     return
% end


%% Names:
EstimatesResults = ['../Results/'  RunName];

ResultsFile      = [EstimatesResults '.mat'];
StepResults      = [EstimatesResults '_step.mat'];


%% Load data:

load(ResultsFile);
load(StepResults);

opt.DataFolder = '../../Data/'; % Overide data location. Just go one folder down.
[FID_Grid,Action,Age,AgeState,~,pproc,DS] = prepdataM10(opt);

%% Bootstrap Sample:
n       = size(DS,1);
sel     = ceil(n*unifrnd(0,1,n,1));	                                         
Action = Action(sel,:); Age = Age(sel,:); AgeState = AgeState(sel,:); DS = DS(sel,:); 
FID_Grid = [1:n]'; % New FID_Grid (if keep the same as before we will have repeated IDs)


%% Substitute Transportation Cost in DS by Bootstraped Transportation Cost
load('../../Data/DataTransCost08212015.mat')

[DataTransCost] = sample_boot(DataTransCost);

e = 1.758; % 2010 exchange rate
% experiment:
%Data = Data(Data.esalq_cost>quantile(Data.esalq_cost,.5),:);
% Covert 2008 esalq price to 2010 prices:
DataTransCost.esalq_cost2010 = DataTransCost.esalq_cost*(301.2898/273.4685);

X = [ones(size(DataTransCost,1),1) DataTransCost.effective_dist/1000]; % Regressors for cost distance regressors (reais)
[b,~,sb,~,ssrEf] = ols(DataTransCost.esalq_cost2010,X);
W = [ones(size(DataTransCost,1),1) DataTransCost.effective_dist/1000]; % Regressors for cost distance regressors (dollars)
[g,~,sg,~,ssrEf] = ols(DataTransCost.esalq_cost2010/e,W);

DS.SugarTransportCostR  =  b(1) + (DS.RoadCostDistance/1000)*b(2); % Sugar transportation cost to closest port in 2010 R$ 
DS.SugarTransportCostUS =  g(1) + (DS.RoadCostDistance/1000)*g(2);

%% Parametric bootstrap of price process:

AgeState = double(AgeState); % AgeState must be in double format for GenStateVariables 
AgeState(AgeState==0) = NaN;
[States,pproc_boot] = GenStateVariablesBoot(DS,opt,AgeState,pproc);
AgeState = int8(AgeState); % Reverse AgeState to int8 format.

opt.IsBoot   = 1; % Set option for Bootsrap estimation. Will load result from the full run as starting point for computational speed purposes.
opt.thetaOld = thetaOld; % Load thetaOld and pOld to opt structure so we can pass to Estimation function. 
opt.pOld     = pOld;
opt.p_uh_old = p_uh_old;

[theta_boot,~,p_unob_het_boot] = AM_Estimation2(FID_Grid,States,AgeState,Action,pproc_boot,opt);

save(SaveBoot,'theta_boot','p_unob_het_boot','pproc_boot');
